package setting_service

import (
	"hytx_media/models"
	"time"
)

/**
	判断需要修改的字段是否在允许修改的时间范围
	@field 字段名
 */
func UserInfoChangeExpire(userId int) bool {
	//判断是否存在修改记录
	var count int
	models.DB.Table("media_user_settings").Where("media_user_id=?",userId).Count(&count)
	if count < 1 {
		//添加一条记录
		models.DB.Table("media_user_settings").Create(&struct {
			MediaUserId int
			ChangeAt time.Time
		}{
			MediaUserId:userId,
			ChangeAt:time.Now(),
		})
		return true
	}
	//修改时间
	changed := models.Changed(userId)
	//是否修改过
	if changed.IsZero() {
		return true
	}
	//判断距离现在是否过去一个月
	now := time.Now()
	diff := timeSub(now, changed)
	if diff > 30 {
		return true
	}
	return false
}

func timeSub(t1, t2 time.Time) int {
	t1 = time.Date(t1.Year(), t1.Month(), t1.Day(), 0, 0, 0, 0, time.Local)
	t2 = time.Date(t2.Year(), t2.Month(), t2.Day(), 0, 0, 0, 0, time.Local)

	return int(t1.Sub(t2).Hours() / 24)
}

func Update(user *models.MediaUser, data map[string]interface{}, webSite string) error {
	//更新用户信息
	err := models.UpdateUserInfo(user.ID, data)
	if err != nil {
		return err
	}
	//判断是否是机构
	if user.Identity == 2 {
		idata := map[string]interface{}{
			"institution_web_site": webSite,
		}
		//更新机构信息
		err = models.UpdateUserInstitution(user.ID, idata)
		if err != nil {
			return err
		}
	}
	//更新用户更新时间
	err = models.UpdateChangeAt(user.ID)
	if err != nil {
		return err
	}
	return nil
}

func GetBindInfo(user *models.MediaUser) map[string]interface{} {
	userInfo, _ := models.GetBindInfo(user.ID)
	isEmail := false
	if userInfo.Email != "" {
		isEmail = true
	}

	isPhone := false
	if user.Phone != "" {
		isPhone = true
	}
	row := models.DB.Table("media_user_settings").Select("watermark").Where("media_user_id=?",user.ID).Row()
	var isWater bool
	row.Scan(&isWater)

	return map[string]interface{}{
		"phone": isPhone,
		"email": isEmail,
		"isWater": isWater,
	}

}